using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Description;
using Microsoft.Practices.Unity;

namespace Ipmce.RemoteVoting.Common.Tools.Wcf.Unity
{
	public class UnityServiceHostFactory : ServiceHostFactory
	{
		/// <summary>
		/// Gets a value indicating whether <see cref="System.ServiceModel.OperationContext"/> support is enabled.
		/// </summary>
		protected virtual bool OperationContextEnabled
		{
			get
			{
				return false;
			}
		}

		/// <summary>
		/// Gets a value indicating whether <see cref="System.ServiceModel.InstanceContext"/> support is enabled.
		/// </summary>
		protected virtual bool InstanceContextEnabled
		{
			get
			{
				return false;
			}
		}

		/// <summary>
		/// Gets a value indicating whether <see cref="System.ServiceModel.ServiceHostBase"/> support is enabled.
		/// </summary>
		protected virtual bool ServiceHostBaseEnabled
		{
			get
			{
				return false;
			}
		}

		/// <summary>
		/// Gets a value indicating whether <see cref="System.ServiceModel.IContextChannel"/> support is enabled.
		/// </summary>
		protected virtual bool ContextChannelEnabled
		{
			get
			{
				return false;
			}
		}

		protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
		{
			ServiceHost serviceHost;

			try
			{
				serviceHost = new ServiceHost(serviceType, baseAddresses);
			}
			catch (Exception e)
			{
				ErrorOnCreatingServiceHost(e);
				throw;
			}

			var behavior = new UnityServiceBehavior(GetContainer())
			{
				ContextChannelEnabled = ContextChannelEnabled,
				InstanceContextEnabled = InstanceContextEnabled,
				OperationContextEnabled = OperationContextEnabled,
				ServiceHostBaseEnabled = ServiceHostBaseEnabled
			};

			serviceHost.Description.Behaviors.Add(behavior);

			CustomizeServiceBehaviors(serviceHost.Description.Behaviors);

			return serviceHost;
		}

		protected virtual void ErrorOnCreatingServiceHost(Exception e)
		{
		}

		protected virtual void CustomizeServiceBehaviors(KeyedByTypeCollection<IServiceBehavior> serviceBehaviors)
		{
		}

		protected virtual IUnityContainer GetContainer()
		{
			return UnityContainerFactory.Create();
		}
	}
}